import path from 'path'
var requestAnimFrame = (function () {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    function (callback) {
      window.setTimeout(callback, 1000 / 60);
    };
})();
export default {
  methods: {
    $getUrlFromLocal (local) {
      let _src = local
      if (_src.match(/^https?:/)) {
        return _src
      }
      let localExist = bbtools.fs.existsSync(local)
      if (!localExist) {
        return bbtools.getAppLogo()
      }

      const buf = bbtools.fs.readFileSync(_src)
      const uint8Buffer = Uint8Array.from(buf)
      const blob = new Blob([uint8Buffer])
      return window.URL.createObjectURL(blob)
    },
    $localImage (src = 'logo') {
      let _src = src
      if (_src === 'logo') {
        return bbtools.getAppLogo()
      }
      return this.$getUrlFromLocal(_src)
      // return this.$getUrlFromLocal(path.resolve(__static, src))
    },
    $localPluginImage (item) {
      if (item.local) {
        return this.$localImage(path.resolve(item.local, '..', item.logo))
      } else {
        return this.$localImage(path.resolve(bbtools.remote.app.getPath('userData'), 'plugins', `${item.pid}@${item.version}.asar`, item.logo))
      }
    },
    $scrollTo (currentY, targetY, ele = window, speed, easing) {
      // targetY: the target scrollY property of the window
      // speed: time in pixels per second
      // easing: easing equation to use

      var scrollY = currentY,
        targetY = targetY || 0,
        speed = speed || 2000,
        easing = easing || 'easeOutSine',
        currentTime = 0;

      // min time .1, max time .8 seconds
      var time = Math.max(.1, Math.min(Math.abs(scrollY - targetY) / speed, .8));

      // easing equations from https://github.com/danro/easing-js/blob/master/easing.js
      var PI_D2 = Math.PI / 2,
        easingEquations = {
          easeOutSine: function (pos) {
            return Math.sin(pos * (Math.PI / 2));
          },
          easeInOutSine: function (pos) {
            return (-0.5 * (Math.cos(Math.PI * pos) - 1));
          },
          easeInOutQuint: function (pos) {
            if ((pos /= 0.5) < 1) {
              return 0.5 * Math.pow(pos, 5);
            }
            return 0.5 * (Math.pow((pos - 2), 5) + 2);
          }
        };

      // add animation loop
      function tick () {
        currentTime += 1 / 60;

        var p = currentTime / time;
        var t = easingEquations[easing](p);

        if (p < 1) {
          requestAnimFrame(tick);

          ele.scrollTo(0, scrollY + ((targetY - scrollY) * t));
        } else {
          ele.scrollTo(0, targetY);
        }
      }

      // call it once to get started
      tick();
    },
    __S4 () {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
    },
    $getUUID (prefix, format = "**-*-*-*-***") {
      return (prefix || '') + format.replace(/(\*)/g, () => this.__S4())
    },
    $timeFormat (ts, format = 'YYYY-MM-DD hh:mm:ss') {
      let nowYear = (new Date()).getFullYear()
      let time = (new Date(ts))
      let year = time.getFullYear()
      let month = time.getMonth() + 1
      month = (month < 10 ? ('0' + month) : month)
      let date = time.getDate()
      date = (date < 10 ? ('0' + date) : date)
      let hour = time.getHours()
      hour = (hour < 10 ? ('0' + hour) : hour)
      let minute = time.getMinutes()
      minute = (minute < 10 ? ('0' + minute) : minute)
      let second = time.getSeconds()
      second = (second < 10 ? ('0' + second) : second)
      let _format = format
      // if (nowYear == year) {
      //   _format = _format.replace(/(YYYY.)/, '')
      // }
      return _format.replace('YYYY', year)
        .replace('MM', month)
        .replace('DD', date)
        .replace('hh', hour)
        .replace('mm', minute)
        .replace('ss', second)
    },
    $timeFormat2 (ts) {
      /**
       * 今天: 今天 09:12
       * 昨天: 昨天 12:12
       * 本月: 2月16日 15:30
       * 其他: 2021年2月14日 18:40
       */
      let now = new Date()
      let nowYear = now.getFullYear()
      let nowMonth = now.getMonth() + 1
      let nowDate = now.getDate()

      let time = (new Date(ts))
      let year = time.getFullYear()
      let month = time.getMonth() + 1
      let date = time.getDate()
      let hour = time.getHours()
      hour = (hour < 10 ? ('0' + hour) : hour)
      let minute = time.getMinutes()
      minute = (minute < 10 ? ('0' + minute) : minute)
      if (nowYear == year && nowMonth == month && nowDate == date) {
        // 今天
        return `今天 ${hour}:${minute}`
      } else if (nowDate == (date + 1)) {
        // 昨天
        return `昨天 ${hour}:${minute}`
      } else {
        return `${year}年${month}月${date}日 ${hour}:${minute}`
      }
    },
    $limitInputNumber (e) {
      /**
         * 限制输入类型  只能为 number
         */
      var et = e || window.event
      var keycode = et.charCode || et.keyCode
      if ((keycode > 57 || keycode < 48) && keycode !== 8 && keycode !== 37 && keycode !== 39 && keycode !== 9) {
        if (window.event) {
          window.event.returnValue = false
        } else {
          e.preventDefault() // for firefox
        }
      }
    },
    $durationFormat (duration) {
      let d = parseInt(Number(duration))
      let h = String(parseInt(d / (60 * 60)))
      let m = String(parseInt((d % (60 * 60)) / 60)).padStart(2, '0')
      let s = String(parseInt(d % 60)).padStart(2, '0')
      return (h > 0 ? h.padStart(2, '0') + ':' : '') + m + ':' + s
    },
    $sizeFormat (size) {
      let out = ''
      if (size > 1 * 1000 * 1000 * 1000) {
        out = parseFloat(size / 1000 / 1000 / 1000).toFixed(1) + ' GB'
      } else if (size > 1000 * 1000) {
        out = parseFloat(size / 1000 / 1000).toFixed(1) + ' MB'
      } else if (size > 1000) {
        out = parseFloat(size / 1000).toFixed(1) + ' KB'
      } else {
        out = parseInt(size) + ' B'
      }
      return out
    },
    $urlFormat () {
      let _query = {}
      let _url = location.search.replace(/^[?]/, '').trim()
      if (_url) {
        _url = _url.split('&')
        _url.forEach(item => {
          if (!_query.hasOwnProperty(item.split('=')[0])) {
            _query[item.split('=')[0]] = item.split('=')[1] || ''
          }
        })
      } else { }
      return _query
    },
    $regStrFormat (str) {
      return str.replace(/(\^|\.|\*|\?|\!|\/|\\|\$|\#|\&|\||,|\[|\]|\{|\}|\(|\)|\-|\+|\=)/g, '\\\\\\$1')
    },
    $initLoginInfo () {
      let loginInfo = bbtools.sendSync('user-info-init')
      if (loginInfo.hasOwnProperty('password')) {
        delete loginInfo.password
      }
      return loginInfo
    },
  }
}